import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.Exception;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PRTokeniser;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;


public class SplitSchedules {
    
    public static String ExtractStudentName_Schedule(byte[] streamBytes) throws IOException {        
        PRTokeniser tokenizer = new PRTokeniser(streamBytes);
        String currentString = "";
        String previousString = "";
        
        while ( tokenizer.nextToken() ) {        	
            if ( tokenizer.getTokenType() == PRTokeniser.TokenType.STRING ) {
            	previousString = currentString;
            	currentString = tokenizer.getStringValue();
            	
            	if ( currentString.startsWith("Day/Period") ) {
            		return previousString.trim();
            	}            
            }
        }
        
        return null;
    }
    

    public static void main(String[] args) throws DocumentException, IOException {        
    	PdfReader reader = null;
    	int totalPages = 0;
    	final String fileName = "DP.pdf";
    	
    	try {
    		reader = new PdfReader(fileName);
    		totalPages = reader.getNumberOfPages();
    		
            System.out.println("There are total " + totalPages + " pages in this input file\n");
            
            for ( int pageNum = 1; pageNum <= totalPages; pageNum++ ) {        	    
            	byte[] streamBytes = reader.getPageContent(pageNum);
            	String studentName = ExtractStudentName_Schedule(streamBytes);
            	
            	if ( studentName != null && studentName.length() > 0 ) {
            		System.out.println(studentName + ".pdf");
            		
            		Document document = new Document(reader.getPageSizeWithRotation(1));
            		PdfCopy writer = new PdfCopy(document, new FileOutputStream(studentName + ".pdf"));
	                PdfImportedPage page = writer.getImportedPage(reader, pageNum);
	    			
	                document.open();
	                writer.addPage(page);
	    			document.close();
	                writer.close();
            	} else {
            		System.out.println("An Error - no student name found at page " + pageNum + "!");
            	}
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	System.out.println("The End.");
        	if ( reader != null ) {
        		reader.close();
        	}
        }
    }
}
